import Vue from "vue";
import axios from "axios";
import store from "../store";
let baseURL =
  process.env.NODE_ENV === "development"
    ? process.env.VUE_APP_BASE_API
    : window.AXIOS_BASE_URL;
const service = axios.create({
  baseURL: baseURL, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 180000, // request timeout
});
service.defaults.withCredentials = true;
let loading;
// 请求拦截
service.interceptors.request.use(
  (config) => {
    if (store.state.token) {
      config.headers["Authorization"] = `Bearer ${store.state.token}`;
    }
    loading = Vue.prototype.$loading({
      lock: true,
      text: "Loading",
      spinner: "el-icon-loading",
      background: "rgba(0, 0, 0, 0.7)",
    });
    // do something before request is sent
    return config;
  },
  (error) => {
    // do something with request error
    console.log(error); // for debug
    return Promise.reject(error);
  }
);

// 拦截response 事先统一处理
service.interceptors.response.use(
  (response) => {
    loading.close();
    const res = response.data;
    if (response.data instanceof Blob) {
      return response.data;
    }
    if (res.code !== 200) {
      // Vue.prototype.$message({
      //   message: res?.message || "Error",
      //   type: "error",
      //   duration: 5 * 1000,
      // });
      console.log("公共请求=", res?.message);

      return Promise.reject(new Error(res?.message || "Error"));
    } else {
      return res;
    }
  },
  (error) => {
    loading.close();
    if (error?.response?.status == 401) {
      store.dispatch("refreshToken");
      Vue.prototype.$bus.$router.push({ path: "/login" });
    } else if (error?.response?.status !== 200) {
      Vue.prototype.$message({
        message: error?.message || "Error",
        type: "error",
        duration: 5 * 1000,
      });
    } else {
      Vue.prototype.$message({
        message: "请求接口错误",
        type: "error",
        duration: 5 * 1000,
      });
    }
    return Promise.reject(error);
  }
);
// 把axios放到全局中
Vue.prototype.$http = service;
export default service;
